<?php
namespace App\Model\Product;


class Attribute extends \Jenssegers\Mongodb\Eloquent\Model
{
    use \App\Plugin\Debuger;
    use \App\Common\Config;

    public function __construct(array $attributes = [])
    {
        $this->connection = self::mongoConn();
        parent::__construct($attributes);

    }


    protected $table = 'attribute';
    public $timestamps = false;

    protected $fillable = [
        'id',
        'type',
        'name',
        'dat',
        'pid',
    ];


    protected static $pid = 0;

    protected static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            $model->pid || $model->pid= static::$pid;
        });
    }

    /**
     * 检测ID是否合法
     * */
    public function isIdValid ()
    {
        $obj = new Product();
        return !$this->pid&&in_array($this->id, $obj->getFillable()) ? self::debug('字段名“'.$this->id.'”不合法，不能与商品基础信息字段重合。') : true;
    }

    /**
     * 检测ID是否已存在
     * @return bool
     * */
    public function isIdExist ():bool
    {
        $qry = static::where('id', $this->id)->where('pid', $this->pid ?? static::$pid);
        $this->_id && $qry->where('_id', '!=', $this->_id);
        return (bool)$qry->count();
    }



    /**
     * 转化成产品属性格式
     * @param $origin array 元数据格式，格式和sub集合一致
     * @param $withPid bool 是否包含于父级ID中，默认true。
     * @return array|null
     * */
    public function toProductJson (array $origin=[], $withinPid=true)
    {
        if (!$this->pid) {
            $dat = [];
            $origin = collect($origin);
            foreach ($this->sub as $attr) {
                $dat[$this->id][$attr->id] = $origin->where('id', $attr->id)->pluck('dat')->first();
            }
            return $withinPid ? $dat : $dat[$this->id];
        }
        return null;
    }




    ### scope作用域
    /**
     * 产品属性检索
     * */
    public function scopeWhereProduct ($query)
    {
        return $query->where('type', 0)->where('pid', 0);
    }



    ### replationship

    public function sub ()
    {
        return $this->hasMany(static::class, 'pid', '_id');
    }



    /**
     * 将属性转化成Excel导出格式
     * @param array
     * */
    public function toExcelArray ()
    {
        if (!$this->pid) {
            $dat = $this->sub->pluck('name', 'id')->toArray();
            $res = [];
            foreach ($dat as $key=>&$val) {
                $res[$this->id.'.'.$key] = $this->name.'.'.$val;
            }
            return $res;
        }
    }
}